package com.example.demo.config

import mu.KLogging
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.builders.WebSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.provisioning.InMemoryUserDetailsManager

@Configuration
@EnableWebSecurity
class OAuth2SecuriyConfig : WebSecurityConfigurerAdapter() {

    @Bean
    override fun userDetailsServiceBean(): UserDetailsService {
        val manager = InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("user_1").password("123456").authorities("USER").build());
        manager.createUser(User.withUsername("user_2").password("123456").authorities("USER").build())
        return manager
    }

    override fun configure(auth: AuthenticationManagerBuilder) {
        super.configure(auth)
    }


//    @Throws(exceptionClasses = Exception::class)
    override fun configure(http: HttpSecurity) {
    super.configure(http)
        http.requestMatchers().anyRequest()
                .and().authorizeRequests().antMatchers("/oauth/*").permitAll()
                .and().authorizeRequests().antMatchers("/login").permitAll()
                .and().authorizeRequests().antMatchers("/demo/*").permitAll()
//                .authorizeRequests().antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
                .and().authorizeRequests().antMatchers("/demo/index*").permitAll()
                .and().httpBasic().disable()
    }

    override fun configure(web: WebSecurity) {
        super.configure(web)
        web.ignoring().antMatchers("/public/**")
    }

    override fun userDetailsService(): UserDetailsService {
        return super.userDetailsService()
    }

    @Bean
    override fun authenticationManagerBean(): AuthenticationManager {
        return super.authenticationManagerBean()
    }

    override fun authenticationManager(): AuthenticationManager {
        return super.authenticationManager()
    }
    companion object : KLogging()

}